<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Post extends AdminBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->helper('file');
        $this->load->model('repo/post_model', 'post_model');
        $this->load->library('mypaging');
    }

    private function intialPaging($option) {
        $this->mypaging->setCount($this->post_model->countPost($option));
        $this->mypaging->setLimit(POST_LIMIT);
        $this->mypaging->setMainURL(admin_post_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function index($pageIndex=1) {
        $option = null;
        $pCase = $this->input->get('f', true);
        if($pCase!= false && $pCase=='trash'){
            $option = array(
                'a.publish_flg' => 0,
                'a.deleted_at'  => null,
                'b.deleted_at'  => null,
                'c.deleted_at'  => null
                );
        }
        $this->intialPaging($option);
        $pagingBar = $this->mypaging->getBar($pageIndex, array('f'=>$pCase));
        $offset    = ($pageIndex-1) * POST_LIMIT;
        $aPost     = $this->post_model->pagingPost(POST_LIMIT, $offset, $option);
        $this->load->model('repo/post_cate_model', 'post_cate_model');
        $aPostCate = $this->post_cate_model->getAllPostCate();
        $aReturn   = array('pageTitle'=>'Tin tức', 'aPost' => $aPost, 'pagingBar'=>$pagingBar, 'aPostCate' => $aPostCate);
        $this->renderView('backend/admin/post/index', $aReturn);
    }

    private function intialSearchPaging($searchKey) {
        $this->mypaging->setCount($this->post_model->countSearchPost($searchKey, array(), true));
        $this->mypaging->setLimit(POST_LIMIT);
        $this->mypaging->setMainURL(admin_post_search_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function search($pageIndex=1) {
        $searchKey = $this->input->get('s', true);
        $this->intialSearchPaging($searchKey);
        $pagingBar = $this->mypaging->getBar($pageIndex, array('s' => $searchKey));
        $offset    = ($pageIndex-1) * POST_LIMIT;
        $aPost     = $this->post_model->searchPagingPost($searchKey, POST_LIMIT, $offset, array(), true);
        $this->load->model('repo/post_cate_model', 'post_cate_model');
        $aPostCate = $this->post_cate_model->getAllPostCate();
        $aReturn   = array(
            'pageTitle' => 'Tìm kiếm | Tin tức',
            'searchkey' => $searchKey,
            'aPost'     => $aPost,
            'pagingBar' => $pagingBar,
            'aPostCate' => $aPostCate
            );
        $this->renderView('backend/admin/post/index', $aReturn);
    }

    private function validate() {
        $this->form_validation->set_rules('post[title]',       'lang:post_title',       'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('post[slug]',        'lang:post_slug',        'trim|required|callback_slug_check|xss_clean');
        $this->form_validation->set_rules('post[order]',       'lang:post_order',       'trim|integer|max_length[6]|xss_clean');
        $this->form_validation->set_rules('post[description]', 'lang:post_description', 'trim|required|max_length[1000]|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
    }

    public function insert() {
        $this->load->model('repo/post_cate_model', 'post_cate_model');
        $aPostCate = $this->post_cate_model->getAllPostCate();
        $oPost = new Post_Entity();
        $oPost->setTitle('Tin tức mới');
        $oPost->setSlug('tin-tuc-moi');
        $oPost->setOrder(1);
        $oPost->setPublishFlg(1);
        $oPost->image_folder = $this->session->userdata('image_folder');
        $aReturn = array(
            'pageTitle' => 'Tin tức mới',
            'aPostCate' => $aPostCate,
            'oPost' => $oPost,
            'action_link' => admin_page_url(POST_SLUG.'/them-moi'));
        $this->renderView('backend/admin/post/single', $aReturn);
    }

    public function doInsert() {
        $aResult = array();
        $date    = new DateTime('now');
        $post    = $this->input->post('post', true);
        $tPost   = $this->input->post('post');
        $this->validate();
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
        } else {
            $postExist = $this->post_model->checkPostExists($post['slug']);
            if($postExist > 0){
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('insert_fail'),
                    'text' => '<ul><li>' . $this->lang->line('post_exist') . '</li></ul>',
                    );
            } else {
                //if change image must check for owner folder
                if(isset($post['image']) && $post['image']!=''){
                    $imageInfo = explode('/', $post['image']);
                    if(count($imageInfo)==2){
                        if ($imageInfo[0] == 'temp') {
                            $this->load->library('MyImage', 'myimage');
                            $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, POST_IMAGE_URL, $imageInfo[1]);
                        }
                        $post['image'] = $imageInfo[1];
                    } else {
                        $post['image'] = NULL;
                    }
                } else {
                    $post['image'] = NULL;
                }

                //set created_at
                $post['updated_at'] = $date->format(DATE_TIME_FORMAT);
                $post['created_at'] = $date->format(DATE_TIME_FORMAT);

                $result = $this->post_model->insert($post);
                if ($result) {
                    $aResult = array('code' => 1, 'text' => $this->lang->line('insert_success'));
                } else {
                    $aResult = array(
                        'code' => 0,
                        'title' => $this->lang->line('system_error'),
                        'text' => $this->lang->line('insert_fail'));
                }
            }
        }
        $this->renderJSON($aResult);
    }

    public function get($slug) {
        $aReturn = array();
        $this->load->model('repo/post_cate_model', 'post_cate_model');
        $oPost = $this->post_model->getPost($slug);
        if($oPost==null){ show_404(); }
        $aPostCate = $this->post_cate_model->getAllPostCate();
        $aReturn = array(
            'pageTitle' => $oPost->getTitle() . ' | Tin tức',
            'oPost' => $oPost,
            'aPostCate' => $aPostCate,
            'action' => 'update',
            'action_link' => admin_page_url(POST_SLUG.'/cap-nhat')
            );
        $this->renderView('backend/admin/post/single', $aReturn);
    }

    private function fullUpdate($post, $tPost){
        $aResult = array();
        $date = new DateTime('now');
        if(isset($post['case']) && $post['case']==UPDATE_CASE_LIST){

        } else {
            $this->form_validation->set_rules('post[content]',     'lang:post_content',     'trim|required|max_length[5000]|xss_clean');
        }
        $this->validate();
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
        } else {
            //set id
            $post_id = $this->encrypt->decode($tPost['id']);
            if($post_id!==false){
                $postExist = $this->post_model->checkPostExists($post['slug'], $post_id);
                if($postExist > 0){
                    $aResult = array(
                        'code' => 0,
                        'title' => $this->lang->line('update_fail'),
                        'text' => '<ul><li>' . $this->lang->line('post_exist') . '</li></ul>',
                        );
                } else {
                    if(isset($post['case']) && $post['case']==UPDATE_CASE_LIST){
                        unset($post['image']);
                    } else {
                        $image_folder = $this->encrypt->decode($tPost['image_folder']);
                        if(isset($tPost['image_folder'])){
                            if($image_folder!=false && $this->image_folder==$image_folder && isset($post['image']) && $post['image']!=''){
                                $imageInfo = explode('/', $post['image']);
                                if(count($imageInfo)==2){
                                    if ($imageInfo[0] == 'temp') {
                                        $this->load->library('MyImage', 'myimage');
                                        $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, POST_IMAGE_URL, $imageInfo[1]);
                                    }
                                    $post['image'] = $imageInfo[1];
                                } else {
                                    $post['image'] = NULL;
                                }
                            }
                        } else {
                            unset($post['image']);
                        }
                        unset($post['image_folder']);
                    }
                    if(isset($post['cate'])&&$post['cate']!=''){
                        $post['post_cate_id'] = $post['cate'];
                        unset($post['cate']);
                    }

                    //set publish_flg
                    if (isset($post['publish_flg']) && $post['publish_flg'] == 1) {
                        $post['publish_flg'] = 1;
                    } else {
                        $post['publish_flg'] = 0;
                    }

                    //set update_at
                    $post['updated_at'] = $date->format(DATE_TIME_FORMAT);

                    //set deleted_at
                    if (isset($post['delete_flg']) && $post['delete_flg'] == 1) {
                        unset($post['updated_at']);
                        $post['deleted_at'] = $date->format(DATE_TIME_FORMAT);
                    } else {
                        $post['deleted_at'] = NULL;
                        $post['updated_at'] = $date->format(DATE_TIME_FORMAT);
                    }

                    unset($post['id']);
                    unset($post['delete_flg']);
                    unset($post['case']);

                    $result = $this->post_model->update($post_id, $post);
                    if ($result) {
                        $aResult = array(
                            'code' => 1,
                            'text' => $this->lang->line('update_success'),
                            'href' => admin_post_url($post['slug']),
                            'front_href' => post_single_url($post['slug'])
                            );
                    } else {
                        $aResult = array(
                            'code' => 0,
                            'title' => $this->lang->line('system_error')
                            );
                    }
                }
            } else {
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('system_error')
                    );
            }
        }
        return $aResult;
    }

    private function flashUpdate($post){
        $aResult = array();
        $date = new DateTime('now');
        //set id
        $post_id = $this->encrypt->decode($post['id']);
        if($post_id!==false){
            unset($post['id']);

            //set publish_flg
            if (isset($post['publish_flg'])) {
                if($post['publish_flg'] == 1){
                    $post['publish_flg'] = 1;
                } else {
                    $post['publish_flg'] = 0;
                }
            }

            //set update_at
            $post['updated_at'] = $date->format(DATE_TIME_FORMAT);

            //set deleted_at
            if (isset($post['delete_flg'])) {
                if($post['delete_flg'] == 1){
                    unset($post['updated_at']);
                    $post['deleted_at'] = $date->format(DATE_TIME_FORMAT);
                } else {
                    $post['deleted_at'] = NULL;
                    $post['updated_at'] = $date->format(DATE_TIME_FORMAT);
                }
            }
            unset($post['delete_flg']);

            $result = $this->post_model->update($post_id, $post);
            if ($result) {
                $aResult = array('code' => 1, 'text' => $this->lang->line('update_success'));
            } else {
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('system_error'),
                    'text' => $this->lang->line('update_fail'));
            }
        } else {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error'),
                'text' => $this->lang->line('update_fail'));
        }
        return $aResult;
    }

    public function doUpdate() {
        $aResult = array();
        $post  = $this->input->post('post', true);
        $tPost = $this->input->post('post');
        if(isset($post['title']) || isset($post['slug']) || isset($post['description']) || isset($post['order']) || isset($post['cate'])){
            $aResult = $this->fullUpdate($post, $tPost);
        } else {
            $aResult = $this->flashUpdate($post);
        }
        $this->renderJSON($aResult);
    }
}
?>